package ru.usu.gv.view;

import ru.usu.gv.uicomponents.UIElementBase;

import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 @author Sergey Pupyrev 
 08.01.2007
 */

public class PickListener
{
	public PickListener()
	{
	}

	private Map<Class, List<IPickingClient>> pickingClients = new HashMap();

	public void register(Class elementClass, IPickingClient pickingClient)
	{
		if (!pickingClients.containsKey(elementClass))
			pickingClients.put(elementClass, new ArrayList());

		pickingClients.get(elementClass).add(pickingClient);
	}

	public void disableAllClients()
	{
		for (List<IPickingClient> list : pickingClients.values())
			for (IPickingClient client : list)
				client.setEnabled(false);
	}

	public void enableAllClients()
	{
		for (List<IPickingClient> list : pickingClients.values())
			for (IPickingClient client : list)
				client.setEnabled(true);
	}

	private List<UIElementBase> pickedList = new ArrayList();
	private int pickedListLimit = Integer.MAX_VALUE;

	public boolean picked(final MouseEvent mevent, UIElementBase element)
	{
		if (!pickingClients.containsKey(element.getClass()))
			return false;

		if (!mevent.isMetaDown() && !mevent.isAltDown())
			if (!pickedList.contains(element))
			{
				element.highlight();
				pickedList.add(element);
				updatePickList();
			}

		for (IPickingClient client : pickingClients.get(element.getClass()))
			if (client.isEnabled())
				client.callback(mevent, element);

		return true;
	}

	private void updatePickList()
	{
		while (pickedList.size() > pickedListLimit)
		{
			UIElementBase head = pickedList.get(0);
			pickedList.remove(0);
			head.unhighlight();
		}
	}

	public List<UIElementBase> getPickedList()
	{
		return pickedList;
	}

	public void setPickedListLimit(int pickedListLimit)
	{
		if (pickedListLimit == -1)
			pickedListLimit = Integer.MAX_VALUE;
		this.pickedListLimit = pickedListLimit;
		updatePickList();
	}

	public void setDefaultState()
	{
		clearPickList();
		setPickedListLimit(1);
	}

	public void clearPickList()
	{
		int oldPickedListLimit = pickedListLimit;
		setPickedListLimit(0);
		setPickedListLimit(oldPickedListLimit);
	}
}
